#include <QtGui/QApplication>
#include <QTranslator>
#include <QTextCodec>
#include <QLocalSocket>
#include <QSplashScreen>
#include <QPainter>
#include <QDir>
#include "mainwindow.h"

#include <xmp.h>

int main(int argc, char *argv[])
{
    xmp_init();
/*    //RawImagePreviewReader reader("/home/cgrimm/Bilder/IMG_9949.CR2", QSize());
    NativeImageReader reader("/home/cgrimm/Bilder/2012/07/20/IMG_2474.JPG", QSize());
    //NativeImageReader reader("/home/cgrimm/Bilder/2011/11/03/IMG_0313.jpg", QSize());
    QDateTime timestamp = reader.metadata("timestamp").toDateTime();
    std::cout << timestamp.toString().toStdString() << std::endl;
    QStringList tags = reader.metadata("keywords").toStringList();
    foreach(QString tag, tags)
        std::cout << "keyword: " << tag.toStdString() << std::endl;
    QImage img = reader.image();
    img.save("test.jpg");
    return 1;*/

    qRegisterMetaType<MediaItemPtr>("MediaItemPtr");
    qRegisterMetaType<QSharedPointer<QPixmap> >("QSharedPointer<QPixmap>");
    QApplication a(argc, argv);

    QLocalSocket sock;
    sock.connectToServer("pio-socket", QIODevice::WriteOnly);
    if(sock.waitForConnected(1000)) {
        sock.write(a.arguments().join("|").toUtf8());
        sock.flush();
        sock.close();
        return 0;
    }

    QPixmap pm(":/images/splash.jpg");
    {
        QPainter p(&pm);
        QRect r(0, pm.height() * 2 / 3, pm.width(), pm.height() / 5);
        QRect br;
        //p.fillRect(r, QColor(255, 255, 255, 128));
        r.adjust(15, 5, -15, -5);
        QFont f;
        f.setPixelSize(pm.height() / 16);
        f.setBold(true);
        p.setFont(f);
        p.setPen(Qt::white);
        p.drawText(r, Qt::AlignLeft, "Photographers Image Organizer", &br);
        r.adjust(0, br.height() + 5, 0, 0);
        f.setPointSize(pm.height() / 24);
        f.setBold(false);
        p.setFont(f);
        p.drawText(r, Qt::AlignLeft, "Version 0.1", &br);
    }
    QSplashScreen splash(pm);
    splash.show();

    QString locale = QLocale::system().name();

    QDir dir = QDir(qApp->applicationDirPath());
    foreach (QString fileName, dir.entryList(QStringList() << "*-" + locale + ".qm", QDir::Files)) {
        QString translation = dir.absoluteFilePath(fileName);
        QTranslator * t = new QTranslator(&a);
        t->load(translation);
        qApp->installTranslator(t);
    }

/*    QTranslator translator;
    translator.load(QString("pio-") + locale);
    a.installTranslator(&translator);*/

    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));

    MainWindow w(&splash);

    return a.exec();
}
